<template>
  <div>
    <div><h1>商品类型列表</h1></div>
  </div>
  <div>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="关键字">
        <el-input
          v-model="searchForm.typeName"
          placeholder="请输入品牌名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="searchForm.typeStatus"
          placeholder="请选择状态"
          clearable
          style="width: 120px"
        >
          <el-option label="隐藏" :value="0" />
          <el-option label="显示" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="loadtree">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div>
    <el-button type="primary" @click="onAddType()">添加类型</el-button>
  </div>

  <div>
    <el-table
      :data="treeList"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      default-expand-all
    >
      <el-table-column prop="id" label="ID" sortable />
      <el-table-column prop="name" label="类型名称" sortable />
      <el-table-column prop="parentId" label="父ID" sortable />
      <el-table-column prop="typeImage" label="图片" sortable>
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            v-if="scope.row.typeImage != null && scope.row.typeImage != ''"
            :src="scope.row.typeImage"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="typeTop" label="排序" sortable />
      <el-table-column prop="typeStatus" label="状态" sortable />
      <el-table-column prop="createTime" label="创建时间" sortable />
      <el-table-column label="操作" sortable>
        <template #default="scope">
          <el-button type="primary" @click="onAddType(scope.row)"
            >添加类型</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible" title="添加类型" width="500">
      <el-form :model="addForm" ref="ruleFormRef" :rules="rules">
        <el-form-item
          label="分类名称"
          :label-width="formLabelWidth"
          prop="typeName"
        >
          <el-input v-model="addForm.typeName" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="分类图片"
          :label-width="formLabelWidth"
          prop="typeImage"
        >
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/prod/type/uploadImages"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth" prop="typeTop">
          <el-input v-model="addForm.typeTop" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="状态"
          :label-width="formLabelWidth"
          prop="typeStatus"
        >
          <el-radio-group v-model="addForm.typeStatus">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getTreeList } from "../api/api";
import { onMounted, reactive, ref } from "vue";

import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";

import { getAddType } from "../api/api";
const ruleFormRef = ref<FormInstance>();
const headers = {
  token: sessionStorage.getItem("token"),
};
const imageUrl = ref("");
//上传图片方法
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = response.data;
};
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const treeList = ref([]);

const searchForm = ref({
  createBy: "",
  createTime: "",
  typeId: null,
  typeImage: "",
  typeName: "",
  typePid: null,
  typeStatus: null,
  typeTop: null,
  updateBy: "",
  updateTime: "",
});

const addForm = ref({
  typeId: null,
  typeImage: "",
  typeName: "",
  typePid: 0,
  typeStatus: 0,
  typeTop: null,
});

//图片校验
const checkAge = (rule: any, value: any, callback: any) => {
  if (
    imageUrl.value == null ||
    imageUrl.value.length == 0 ||
    imageUrl.value == ""
  ) {
    return callback(new Error("请输入图片"));
  }
  callback();
};

//添加校验
const rules = reactive<FormRules>({
  typeName: [{ required: true, message: "请输入类型名称", trigger: "blur" }],
  typeTop: [{ required: true, message: "请输入排序", trigger: "blur" }],
  typeImage: [{ required: true, validator: checkAge, trigger: "blur" }],
  typeStatus: [
    {
      required: true,
      message: "请选择状态",
      trigger: "change",
    },
  ],
});

//添加类型
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onHandlerAddType();
    } else {
      console.log("error submit!", fields);
    }
  });
};

//添加类型
const onHandlerAddType = () => {
  addForm.value.typeImage = imageUrl.value;
  getAddType(addForm.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      dialogFormVisible.value = false;
      loadtree();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//显示添加分类框
const onAddType = (row: any) => {
  addForm.value = {
    typeId: null,
    typeImage: "",
    typeName: "",
    typePid: 0,
    typeStatus: 0,
    typeTop: null,
  };
  imageUrl.value = "";
  if (row != null) {
    addForm.value.typePid = row.id;
  }
  dialogFormVisible.value = true;
};

const loadtree = () => {
  getTreeList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      treeList.value = res.data.data;
    }
  });
};

onMounted(() => {
  loadtree();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
